﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SpotifyRemote
{
	class Spotify : HttpServer.HttpModules.HttpModule
	{
		public Spotify()
		{
			_API = new SpotifyAPI.SpotifyAPI();
			_API.Initialize();
		}

		SpotifyAPI.SpotifyAPI _API;

		public override bool Process(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session)
		{
			bool returnSong = false;
			bool handled = false;

			// Perform any request spotify action
			if (request.UriParts.Length > 0 && request.UriParts[0] == "playpause")
			{
				_API.PlayPause();
				returnSong = true;
				handled = true;
			}

			if (request.UriParts.Length > 0 && request.UriParts[0] == "next")
			{
				_API.Next();
				returnSong = true;
				handled = true;
			}

			if (request.UriParts.Length > 0 && request.UriParts[0] == "previous")
			{
				_API.Previous();
				returnSong = true;
				handled = true;
			}

			// Return song info
			if (request.UriParts.Length > 0 && request.UriParts[0] == "song")
			{
				returnSong = true;
				handled = true;
			}

			if (returnSong)
			{
				System.Threading.Thread.Sleep(500);
				StreamWriter writer = new StreamWriter(response.Body);
				if (!_API.IsPlaying)
					writer.Write("pause");
				else
					writer.Write(_API.Track.Artist + "\n" + _API.Track.Title);
				writer.Flush();

			}

			// Return an embedded page
			else if (!handled)
			{
				if (request.UriPath == "/")
					request.UriPath = "/index.htm";

				System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
				SetContentType(response, request.UriPath);

				try
				{
					string path = assembly.GetName().Name.ToString() + ".html" + request.UriPath.Replace('/', '.');

					Stream req_file = assembly.GetManifestResourceStream(path);

					if (request.UriPath == "/index.htm")
					{
						StreamWriter writer = new StreamWriter(response.Body);
						string data = new StreamReader(req_file).ReadToEnd().Replace("<!-- Title -->", _API.Track.Title).Replace("<!-- Artist -->", _API.Track.Artist).Replace("<!-- PlayImg -->", (_API.IsPlaying ? "pause" : "play"));
						writer.Write(data);
						writer.Flush();
						//writer.Dispose();
					}
					else
					{
						byte[] buffer = new byte[1024];
						int l = 0;
						while ((l = req_file.Read(buffer, 0, 1024)) > 0)
						{
							response.Body.Write(buffer, 0, l);
						}
					}
				}
				catch { }
			}


			return true;

			//StreamWriter writer = new StreamWriter(response.Body);
			//writer.WriteLine("Hey man");
			//writer.Flush();

			/*string req = "index.htm";
			string req_file = Path.GetFileName(request.UriPath);
			if (req_file == "reset.css" ||
				req_file == "style.css")
				req = request.UriParts[0];

			string req_type = req.Split(new[] { "." }, StringSplitOptions.None).Last();
			if (req_type == "css")
				response.ContentType = "text/plain";

			System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
			StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(assembly.GetName().Name.ToString() + ".html." + req));

			StreamWriter writer = new StreamWriter(response.Body);
			string data = reader.ReadToEnd();

			if (req == "index.htm")
			{
				StringBuilder items = new StringBuilder();
				foreach (IPlugin p in _Plugins)
				{
					foreach (Button b in p.Buttons)
					{
						items.AppendLine("			<li class=\"item button\">");
						items.AppendLine("				<a href=\"" + p.GetType().Name.ToLower().Replace("Controller", "") + "/" + b.ActionURL + "\">" + b.Caption + "</a>");
						items.AppendLine("			</li>");
					}
				}

				data = data.Replace("<!--items-->", items.ToString());
				items = null;
			}
			else if (req == "style.css")
			{
				data = data.Replace("/*buttonsize", Properties.Settings.Default.ButtonSize.ToString());
			}
			req_file = null;

			writer.Write(data);
			data = null;
			writer.Flush();

			return true;*/
		}

		private void SetContentType(HttpServer.IHttpResponse response, string filename)
		{
			switch (Path.GetExtension(filename).ToLower())
			{
				case ".htm": response.ContentType = "text/html"; break;
				case ".css": response.ContentType = "text/css"; break;
				case ".js": response.ContentType = "text/javascript"; break;
				case ".png": response.ContentType = "image/png"; break;
			}
		}
	}
}
